package banner

import (
	"context"
	"go_final/mxshop_api/goods_web/api"
	"go_final/mxshop_api/goods_web/forms"
	"go_final/mxshop_api/goods_web/global"
	goodspb "go_final/mxshop_api/goods_web/proto/protofile"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"google.golang.org/protobuf/types/known/emptypb"
)

func List(c *gin.Context) {
	res, err := global.GoodsClient.BannerList(context.Background(), &emptypb.Empty{})
	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Create(c *gin.Context) {
	bannerForm := forms.Banner{}
	err := c.ShouldBind(&bannerForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	res, err := global.GoodsClient.CreateBanner(context.Background(), &goodspb.BannerRequest{
		Index: bannerForm.Index,
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Delete(c *gin.Context) {
	bannerID := c.Param("id")
	bannerIDInt, _ := strconv.Atoi(bannerID)

	res, err := global.GoodsClient.DeleteBanner(context.Background(), &goodspb.BannerRequest{
		Id: int32(bannerIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Update(c *gin.Context) {
	bannerID := c.Param("id")
	bannerIDInt, _ := strconv.Atoi(bannerID)

	bannerForm := forms.Banner{}
	err := c.ShouldBind(&bannerForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	res, err := global.GoodsClient.UpdateBanner(context.Background(), &goodspb.BannerRequest{
		Id:    int32(bannerIDInt),
		Index: bannerForm.Index,
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}
